package com.araaya.eslimsmobile;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.araaya.eslimsmobile.R;
import com.araaya.eslimsmobile.db.DatabaseFunction;
import com.araaya.eslimsmobile.db.GPSLand;
import com.araaya.eslimsmobile.gps.MobileKmlWriter;
import com.araaya.eslimsmobile.util.ElandConstant;
import com.araaya.eslimsmobile.web.WebCaller;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class LandListForAdjacentLand extends ListActivity {

	ListAdapter adapter;
	ArrayList<HashMap<String, String>> landList;

	private EditText txtSearch;
	int textlength = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.land_list);

		txtSearch = (EditText) findViewById(R.id.txtSearch);

		landList = new ArrayList<HashMap<String, String>>();
		landList = loadLandList();

		if (landList.size() == 0) {
			finish();
			Toast.makeText(LandListForAdjacentLand.this,
					ElandConstant.NO_LAND_DB_STR, Toast.LENGTH_LONG).show();
		}

		adapter = new SimpleAdapter(this, landList, R.layout.land_list_view,
				new String[] { "landname" }, new int[] { R.id.item_title });

		setListAdapter(adapter);

		// on click the List
		final ListView lv = getListView();
		lv.setLongClickable(true);
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				@SuppressWarnings("unchecked")
				final HashMap<String, String> o = (HashMap<String, String>) lv
						.getItemAtPosition(position);

				landListAlert(o.get("landname"), o.get("coordinates"));

			}

		});

		txtSearch.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				String searchTxt = txtSearch.getText().toString();
				if (searchTxt != null && searchTxt.length() > 0) {
					landList = loadLandListByLandName(searchTxt);

				} else {
					landList = loadLandList();
				}
				adapter = new SimpleAdapter(LandListForAdjacentLand.this,
						landList, R.layout.land_list_view,
						new String[] { "landname" },
						new int[] { R.id.item_title });

				setListAdapter(adapter);

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

	}

	private ArrayList<HashMap<String, String>> loadLandList() {

		DatabaseFunction databaseFunction = new DatabaseFunction(
				LandListForAdjacentLand.this);
		ArrayList<HashMap<String, String>> landList = new ArrayList<HashMap<String, String>>();

		List<GPSLand> gpsLands = new ArrayList<GPSLand>();
		gpsLands = databaseFunction.getAllGPSLands();
		if (gpsLands.size() > 0) {

			for (int i = 0; i < gpsLands.size(); i++) {
				GPSLand gland = gpsLands.get(i);
				HashMap<String, String> map = new HashMap<String, String>();
				if (gland != null) {
					map.put("id", "" + gland.getId());
					map.put("landname", gland.getLandName());
					map.put("coordinates", gland.getCoordinates());
					landList.add(map);
					Log.d("NAME==>", gland.getLandName());
					Log.d("MapNAME==>", map.get("landname"));
				}

			}

		}
		return landList;

	}

	private ArrayList<HashMap<String, String>> loadLandListByLandName(
			String landName) {

		DatabaseFunction databaseFunction = new DatabaseFunction(
				LandListForAdjacentLand.this);
		ArrayList<HashMap<String, String>> landList = new ArrayList<HashMap<String, String>>();

		List<GPSLand> gpsLands = new ArrayList<GPSLand>();
		gpsLands = databaseFunction.getGPSLandsByName(landName);
		if (gpsLands.size() > 0) {

			for (int i = 0; i < gpsLands.size(); i++) {
				GPSLand gland = gpsLands.get(i);
				HashMap<String, String> map = new HashMap<String, String>();
				if (gland != null) {
					map.put("id", "" + gland.getId());
					map.put("landname", gland.getLandName());
					map.put("coordinates", gland.getCoordinates());
					landList.add(map);
					Log.d("NAME==>", gland.getLandName());
					Log.d("MapNAME==>", map.get("landname"));
				}

			}

		}
		return landList;

	}

	private void landListAlert(final String landName, final String coordinate) {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage("Land : " + landName)
				.setCancelable(false)
				.setPositiveButton("Show Map",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								// mapTypeViewAlert(coordinate);
								if (KmlHome.pointList != null) {
									KmlHome.pointList.clear();
								}

								Intent i = new Intent(getApplicationContext(),
										MyMapViewerAdjacentLand.class);
								i.putExtra("coordinate", coordinate);
								startActivity(i);
								finish();
								return;

							}
						})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								dialog.cancel();
								return;

							}
						});

		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		// alert.setTitle("eLand Mobile");
		alert.setTitle("Show the Map");
		// Icon for AlertDialog
		alert.setIcon(R.drawable.land);
		alert.show();

	}

	// Message Alert
	public void displayAlert(String message, String title, String btnTxt,
			Integer image) {

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(message)
				.setCancelable(false)
				.setPositiveButton(btnTxt,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								dialog.cancel();
								return;

							}
						});

		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(title);
		// Icon for AlertDialog
		alert.setIcon(image);
		alert.show();
	}

	private void mapTypeViewAlert(final String coordinate) {

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage("Select Your Map Type")
				.setCancelable(false)
				.setPositiveButton("Show Map",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								Intent i = new Intent(getApplicationContext(),
										MyMapViewerAdjacentLand.class);
								i.putExtra("coordinate", coordinate);
								startActivity(i);

								return;

							}
						})

				.setNeutralButton("Map With Area",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								MobileKmlWriter kmlWriter = new MobileKmlWriter();
								String middlePoint = kmlWriter
										.getMiddlePoint(coordinate);
								long refNo = kmlWriter.getReferenceNo();

								Intent i = new Intent(getBaseContext(),
										WebHome.class);
								i.putExtra("coordinate", coordinate);
								i.putExtra("middlePoint", middlePoint);
								i.putExtra("refNo", refNo);
								startActivity(i);

								return;

							}
						});

		AlertDialog alert = alt_bld.create();
		alert.setTitle("View Map");
		// Icon for AlertDialog
		alert.setIcon(R.drawable.land);
		alert.show();

	}

}
